package com.zcg.blogger.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.zcg.blogger.pojo.Pager;
import com.zcg.blogger.util.PattemUtil;

/**
 * 分页过滤器
 * Servlet Filter implementation class pagerFilter
 */
public class pagerFilter implements Filter {

	static final int pageSize = 10;

	/**
	 * Default constructor.
	 */
	public pagerFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		Pager pager = Pager.getPager();
		pager.setPageNo(getPageNo(httpRequest));
		pager.setPageOffset(getPageOffset(getPageNo(httpRequest)));
		pager.setPageSize(pageSize);
		request.setAttribute("pageNo", pager.getPageNo());
		try {
			chain.doFilter(request, response);
		} finally {
			// 清空ThreadLocal中的值
			pager.setPageOffset(0);
		}
	}

	private int getPageOffset(int pageNo) {
		return (pageNo - 1) * pageSize;
	}

	protected int getPageNo(HttpServletRequest request) {
		int no = 0;
		try {
			String pageNo = request.getParameter("pageNo");
			if (pageNo == null || PattemUtil.number(pageNo)
					|| PattemUtil.zero(pageNo)) {
				no = 1;
			} else {
				no = Integer.parseInt(pageNo);
			}
		} catch (NumberFormatException ignore) {
			ignore.printStackTrace();
		}
		return no;
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
